import {PlusOutlined} from '@ant-design/icons';
import {ActionType, ProColumns, ProTable} from '@ant-design/pro-components';
import {Button, message, Popconfirm} from 'antd';
import React, {useRef, useState} from 'react';
import {
  addFaqAPI,
  deleteFaqAPI,
  pageFaqAPI,
  updateFaqAPI
} from './service';
import FaqForm from './components/FaqForm';
import {listFaqCategoryAPI} from "@/pages/faq/faq-category/service";

const FaqManagement: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [categoryOptions, setCategoryOptions] = useState<{ label: string; value: number }[]>([]);

  // 加载分类选项
  const loadCategoryOptions = async () => {
    try {
      const {data} = await listFaqCategoryAPI({});
      setCategoryOptions(data.map((item: API.IFaqCategory) => ({
        label: item.name,
        value: item.id
      })));
    } catch (error) {
      message.error('加载分类失败');
    }
  };

  // 处理删除
  const handleDelete = async (id: string | undefined) => {
    if (!id) {
      message.error('请选择要删除的问题');
      return;
    }
    try {
      const {data} = await deleteFaqAPI(id);
      if (data) {
        message.success('删除成功');
        actionRef.current?.reload();
      }
    } catch (error) {
      message.error('删除失败，请重试');
    }
  };

  // 表格列配置
  const columns: ProColumns<API.IFaq>[] = [
    {
      title: '问题分类',
      dataIndex: 'categoryName',
      key: 'categoryName',
      hideInSearch: true,
    },
    {
      title: '问题内容',
      dataIndex: 'question',
      key: 'question',
      ellipsis: true,
    },
    {
      title: '浏览次数',
      dataIndex: 'viewCount',
      key: 'viewCount',
      search: false,
    },
    {
      title: '点赞次数',
      dataIndex: 'likeNum',
      key: 'viewCount',
      search: false,
    },
    {
      title: '点踩次数',
      dataIndex: 'uselessNum',
      key: 'viewCount',
      search: false,
    },
    {
      title: '热门问题',
      dataIndex: 'isHot',
      key: 'isHot',
      valueEnum: {
        "0": {text: '是', status: 'Success'},
        "1": {text: '否', status: 'Default'},
      },
    },
    {
      title: '推荐问题',
      dataIndex: 'isRecommend',
      key: 'isRecommend',
      valueEnum: {
        "0": {text: '是', status: 'Success'},
        "1": {text: '否', status: 'Default'},
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      valueEnum: {
        "0": {text: '启用', status: 'Success'},
        "1": {text: '禁用', status: 'Error'},
      },
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      render: (text, record) => [
        <FaqForm
          key="edit"
          formType="edit"
          initialValues={record}
          onFinish={async (values) => {
            const {data} = await updateFaqAPI({...values, id: record?.id});
            if (data) {
              message.success('添加成功');
              actionRef.current?.reload();
            }
            return data
          }}
          categoryOptions={categoryOptions}
          trigger={<a>编辑</a>}
        />,
        <Popconfirm
          key="delete"
          title="确定要删除这个常见问题吗?"
          onConfirm={() => handleDelete(record.id)}
          okText="确定"
          cancelText="取消"
        >
          <a style={{color: 'red'}}>删除</a>
        </Popconfirm>,
      ],
    },
  ];

  return (
    <ProTable<API.IFaq>
      headerTitle="常见问题管理"
      actionRef={actionRef}
      rowKey="id"
      search={{
        labelWidth: "auto",
        span: 6,
      }}
      pagination={{
        pageSize: 10,
      }}
      toolBarRender={() => [
        <FaqForm
          key="create"
          formType="create"
          onFinish={async (values) => {
            const {data} = await addFaqAPI(values);
            if (data) {
              message.success('添加成功');
              actionRef.current?.reload();
            }
            return data
          }}
          categoryOptions={categoryOptions}
          trigger={
            <Button type="primary" onClick={loadCategoryOptions}>
              <PlusOutlined/> 新建问题
            </Button>
          }
        />,
      ]}
      request={async (params) => {
        const {data} = await pageFaqAPI(params);
        return data;
      }}
      size={'small'}
      columns={columns}
    />
  );
};

export default FaqManagement;
